
import { Component, OnInit,ViewChild} from '@angular/core';
import {DrawService,TipService,DcTablePagingPipe,ModalService,HttpService} from 'itcloud-plugin';
import { DetailNoticeComponent } from './detail-notice/detail-notice.component';
import { AddNoticeComponent } from '../add-notice/add-notice.component';
import { GetPathService } from '../get-path.service';
import { CloseTimeTipComponent } from './close-time-tip/close-time-tip.component';

@Component({
  selector: 'app-my-found',
  templateUrl: './my-found.component.html',
  styleUrls: ['./my-found.component.css']
})
export class MyFoundComponent implements OnInit {

    //分页
    pager;
    cookies:any;
    param:any={
        searchType:0,
        limit: 10,
        page: 1
    };
    tableId: string;
    tableLoading: boolean;
    ifShowHide:boolean=true;
    tableOptions = {
       // maxHeight: '200px',
       // minHeight: '100px',
       checkbox: false,
       loading: true,
       showIndex: false
    };
    constructor(
        private drawService: DrawService,
        private modal: ModalService,
        private http:HttpService,
        private GetPathService:GetPathService,
        private tipService:TipService
    ) { }
    headerConfig = [
        {
            field: 'infoCode', // 显示字段
            title: '公告编号', // 表头显示
            canSort: false, // 是否可排序
            width: '10%', // 单元格宽度
            filter: { // 过滤配置
                type: 'text', // 过滤类型
                defaultText: this.param.infoName,
                offset: 'right', // 过滤框是否右偏移
                fn: (filter) => { // 过滤回调方法
                    //console.log(filter, 'infoCode','公告编号');
                    this.param.infoCode = filter;
                    this.getDataInit();
                }
            },
            hideTitle: true,
        }, 
        {
            field: 'infoName', // 显示字段
            title: '公告主题', // 表头显示
            width: '20%', // 单元格宽度
            hideTitle: false,
            flex: '1', // 单元格自适应宽度优先级,
            filter: { // 过滤配置
                type: 'text', // 过滤类型
                offset: 'right', // 过滤框是否左偏移
                fn: (filter) => { // 过滤回调方法
                    //console.log(filter, 'infoName',"公告主题");
                    this.param.infoName = filter;
                    this.getDataInit();
                }
            },
            /*alignTd: 'center',
            alignTh: 'center',*/
        }, 
        {
            field: 'createName', // 显示字段
            title: '创建人', // 表头显示
            canSort: false, // 是否可排序
            width: '10%', // 单元格宽度
            isGroup: false,
            hideTitle: true,
            hideHeaderGroup: false,
            filter: { // 过滤配置
            type: 'text', // 过滤类型
            offset: 'right', // 过滤框是否左偏移
            fn: (filter) => { // 过滤回调方法
                //console.log(filter, 'index');
                this.param.createName = filter;
                this.getDataInit();
            }
                
            },
            /*alignTd: 'center',
            alignTh: 'center',*/
        }, 
        {
            field: 'infoStatus', // 显示字段
            title: '状态', // 表头显示
            width: '10%', // 单元格宽度
            hideTitle: true,
            filter: {
                type: 'checkList',
                optionList: [
                    {
                        checked: false,
                        name: '未发布',
                        status:0
                    }, {
                        checked: false,
                        name: '已发布',
                        status:1
                    }, {
                        checked: false,
                        name: '已关闭',
                        status:2
                    }
                ],
                option: {
                    maxHeight: '150px',
                    filterKey: 'name'
                },
                fn: (filter) => {
                    //console.log(filter, 'infoStatus');
                    let statusStr = '';
                    filter.map(function(item,i){
                        //console.log(item,i);
                        statusStr +=  (filter.length-1 === i ? item.status : item.status+',');    
                    });
                    //console.log(statusStr,'statusStr');
                    this.param.status = statusStr;
                    this.getDataInit();
                }
            }
        }, 
        {
        field: 'infoType', // 显示字段
        title: '类型', // 表头显示
        canSort: false, // 是否可排序
        width: '10%', // 单元格宽度
        filter: { // 过滤配置
            type: 'checkList',
            optionList: [
                {
                    checked: false,
                    name: '公告通知',
                    type:0
                }, {
                    checked: false,
                    name: '信息交流',
                    type:1
                }
            ],
            option: {
            maxHeight: '150px',
            filterKey: 'name'
            },
            fn: (filter) => {
                //console.log(filter, 'infoType');
                if(filter.length!==0){
                    this.param.type = (filter.length>1 ? '' : filter[0].type);
                }
                this.getDataInit();
                //if(filter.length>1){}
            }
        },
        hideTitle: true,
        /*alignTd: 'center',
        alignTh: 'center',*/
        }, 
        {
            field: 'closeTime', // 显示字段
            title: '关闭时间', // 表头显示
            canSort: true, // 是否可排序
            width: '10%', // 单元格宽度
            hideTitle: true,
            isGroup: false,
            hideHeaderGroup: false,
            /*alignTd: 'center',
            alignTh: 'center',*/
        }, 
        {
            field: 'action', // 显示字段
            title: '操作', // 表头显示
            width: '15%', // 单元格宽度
            hideTitle: true
        }
    ];
    tableData = [];
    // @ViewChild('tableNew') tableNew;
    //初始化
    ngOnInit() {
        this.cookies= this.getCookie('userId');
        this.param.userId= this.cookies;
        this.pager = {
            total: 0,
            limit: 10,
            page: 1
        };
        this.checkUser();   
    }
    checkUser(){
        let param = {
            userId:this.cookies,
            //syncId:"208929388467580928",//208948191939260416
            module:'infoList'
        }
        this.http.getData({
            url: this.GetPathService.AjaxPath.bulletinServer+'/login/checkUser',
            search: param,
            }).subscribe(res => {
                //console.log(res['result']);
                if(res['returnCode'] === '0000'){
                    this.ifShowHide = true;
                    this.getDataInit();
                    //this.tipService.show({ type: 'error', title: res['returnMessage']});
                }else if(res['returnCode'] === '6002'){
                    this.ifShowHide = false;
                }else{
                    this.tipService.show({ type: 'error', title: res['returnMessage']}); 
                }
            }, err => {this.tipService.show({ type: 'error', title: "加载失败"}); });
    }
    getCookie(name){
        let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))return decodeURI(arr[2]);
        else return null;
    }
    getDataInit(){
        this.http.getData({
            url: this.GetPathService.AjaxPath.bulletinServer+'/bulletin/bulletinList',
            search: this.param,
            }).subscribe(res => {
                if(res['returnCode'] === '0000'){
                    this.tableOptions.loading = false;
                    this.pager.total= res['result'].allRows;
                    this.disposeData(res['result'].result);
                }else{
                    this.tipService.show({ type: 'success', title: res['returnMessage']});
                }
            }, err => { this.tipService.show({ type: 'error', title: "加载失败"});})
    }
    //处理数据
    disposeData(data){
        for(let i=0;i<data.length;i++){
        data[i].closeTime = this.timeStamp(data[i].closeTime);
        data[i].infoTypeName = (data[i].infoType === 0 ? '公告通知' : '信息交流');
        data[i].infoStatusName = (data[i].infoStatus === 0 ? '未发布' : (data[i].infoStatus === 1 ? '已发布' : '已关闭')) 
        }
        this.tableData = data;
    }
    //时间戳转换成时间
    timeStamp(timestamp){
        let Y,M,D,h,m,s;
            let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            //var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            Y = date.getFullYear() + '-';
            M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
            D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
            h = (date.getHours() < 10 ? '0'+ date.getHours() : date.getHours()) + ':';
            m = (date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes()) + ':';
            s = (date.getSeconds()< 10 ? '0'+ date.getSeconds() : date.getSeconds());
            return Y+M+D+h+m+s;
    }
    //排序
    sortEvent(ev: any) {
        this.pager = {
            total: 0,
            limit: 10,
            page: 1
        };
        this.param.sortField= ev.field;
        this.param.sorting= (ev.sort ==='desc' ? '-1' : (ev.sort === 'asc' ? '1' : ''));
        this.getDataInit();
    }
    //获取节点----侧滑
    findItemByKey(dataList) {
        console.log(dataList);
        const result = this.drawService.open({
            handler: (type) => { // 传入侧滑component的方法，在component中用@Input() handler:any;接收
                result.closeComponent();
                this.getDataInit();
            },
            data: dataList,
            component:DetailNoticeComponent, // 侧滑内容的component
            iconCls: '',
            title: '公告详情', // 侧滑是否有title
            padding: '10px 0 0 0', // 侧滑内容的padding值
            width: '80%', // 侧滑宽度
            hiddenScroll: false, // 隐藏侧滑的滚动条，使用程序自己的滚动条
        });
    }
    findItemByKeyEdit(dataList){
        const result = this.drawService.open({
            handler: (type) => { // 传入侧滑component的方法，在component中用@Input() handler:any;接收
                result.closeComponent();
                this.getDataInit();
            },
            data: dataList,
            component: AddNoticeComponent, // 侧滑内容的component
            iconCls: '',
            title: ' 编辑公告', // 侧滑是否有title
            padding: '10px 0 0 0', // 侧滑内容的padding值
            width: '80%', // 侧滑宽度
            hiddenScroll: false, // 隐藏侧滑的滚动条，使用程序自己的滚动条
        });
    }
    // 切换页码
    nowPageChange(ev) {
        this.pager.page = ev;
        this.param.page = ev;
        this.getDataInit();
        // this.getAdviceTableData();
    }
    //关闭
    udateStatusClose(data){
        let paramStatus=null;
        paramStatus = {
            infoId:data.id,
            operation:1
        } 
        this.http.getData({
            url: this.GetPathService.AjaxPath.bulletinServer+'/bulletin/udateStatus',
            search: paramStatus,
          }).subscribe(res => {
            if(res['returnCode']==='0000'){
                this.tipService.show({ type: 'success', title: res['returnMessage']});
                this.getDataInit();
              }
          }, err => {this.tipService.show({ type: 'error', title: "加载失败"}); })
        
    }
    //打开
    udateStatusOpen(data){
        const result = this.modal.open({
            title: '请重新选择关闭时间',
            component: CloseTimeTipComponent,
            backdropCloseable: false,
            width: '500px',
            data: data,
            handler: (data) => {
              console.log(data);
              result.modalInstance.hide();
              this.getDataInit();
            }
          });


        
    }
    //删除
    deleteNotice(id){
        this.http.getData({
            url: this.GetPathService.AjaxPath.bulletinServer+'/bulletin/deleteNotice/'+id,
          }).subscribe(res => {
              if(res['returnCode']==='0000'){
                this.tipService.show({ type: 'success', title: res['returnMessage']});
                this.getDataInit();
              }
          }, err => {this.tipService.show({ type: 'error', title: "加载失败"}); })
    }


}
